package com.ln.lnzw.activity;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.LogUtils;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.ln.lnzw.R;
import com.ln.lnzw.app.AppConstant;
import com.ln.lnzw.base.BaseActivity;
import com.ln.lnzw.bean.CenterDetailBean;
import com.ln.lnzw.bean.CityJsonBean;
import com.ln.lnzw.bean.HeadBean;
import com.ln.lnzw.bean.ImplementationSubjectBean;
import com.ln.lnzw.bean.JsonBean;
import com.ln.lnzw.bean.SettingsPersonalBean;
import com.ln.lnzw.bean.UserDetailNewBean;
import com.ln.lnzw.bean.UserPicBean;
import com.ln.lnzw.net.HttpMethods;
import com.ln.lnzw.utils.BitmapUtil;
import com.ln.lnzw.utils.GetJsonDataUtil;
import com.ln.lnzw.utils.ImageUtil;
import com.ln.lnzw.utils.ToastFactory;
import com.ln.lnzw.view.ClearableEditText;
import com.ln.lnzw.view.CommonPopupWindow;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by wuwei on 2018/3/29.
 * 个人资料
 */

public class PersonalInformationSettingsActivity extends BaseActivity implements View.OnClickListener, CommonPopupWindow.ViewInterface {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_nicheng)
    TextView tvNicheng;
    @BindView(R.id.rl_nicheng)
    RelativeLayout rlNicheng;
    @BindView(R.id.tv_dianhua)
    TextView tvDianhua;
    @BindView(R.id.rl_dianhua)
    RelativeLayout rlDianhua;
    @BindView(R.id.tv_zhenshixingming)
    TextView tvZhenshixingming;
    @BindView(R.id.rl_zhenshixingming)
    RelativeLayout rlZhenshixingming;
    @BindView(R.id.tv_shenfenzhenghao)
    TextView tvShenfenzhenghao;
    @BindView(R.id.rl_shenfenzhenghao)
    RelativeLayout rlShenfenzhenghao;
    @BindView(R.id.tv_youxiang)
    TextView tvYouxiang;
    @BindView(R.id.rl_youxiang)
    RelativeLayout rlYouxiang;
    @BindView(R.id.tv_juzhudiqu)
    TextView tvJuzhudiqu;
    @BindView(R.id.rl_juzhudiqu)
    RelativeLayout rlJuzhudiqu;
    @BindView(R.id.tv_xiangxidizhi)
    TextView tvXiangxidizhi;
    @BindView(R.id.rl_xiangxidizhi)
    RelativeLayout rlXiangxidizhi;
    @BindView(R.id.nickname)
    TextView nickname;
    @BindView(R.id.rl_xiugaitouxaing)
    RelativeLayout rlXiugaitouxaing;
    @BindView(R.id.civ_image_head)
    CircleImageView civImageHead;
    private Thread thread;
    CommonPopupWindow popupWindow;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private boolean isLoaded = false;
    private ArrayList<JsonBean> options1Items1 = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items2 = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items3 = new ArrayList<>();
    private List<CityJsonBean.ResultBean> options1Items = new ArrayList<>();
    private List<List<CityJsonBean.ResultBean.CityBean>> options2Items = new ArrayList<>();
    private List<List<List<CityJsonBean.ResultBean.CityBean.CountyBean>>> options3Items = new ArrayList<>();
    private View layout;
    private TextView textView;
    private AlertDialog dailog;
    private ClearableEditText clearableEditText;
    private Uri uri;
    File outputImage;
    File photoFile;
    private Uri imageUri;
    private Bitmap bitmap;
    public static final int Cut_PHOTO = 1;
    public static final int SHOW_PHOTO = 2;
    public static final int PHOTO_ALBUM = 3;
    public static final int SHOW_PHOTO_ALBUM = 4;
    public Uri imageUriFromCamera;
    public final String USER_IMAGE_NAME = "image.png";
    private static final String TAG = "PersonalInformationSett";
    private String token;
    private String loginAccountName;
    private String password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_information_settings);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        initData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().post("change");

    }

    @Subscribe
    public void onEvent(String isLogin) {
        if ("address".equals(isLogin)) {
            tvXiangxidizhi.setText(spUtils.getString(AppConstant.ADDRESS));
        }
    }

    private void initData() {
        token = activity.spUtils.getString(AppConstant.TOKEN);
        loginAccountName = activity.spUtils.getString(AppConstant.LOGINACCOUNTNAME);
        password = activity.spUtils.getString(AppConstant.PASSWORD);
        HttpMethods.getInstanceCenter().info.getUserDetail(token,loginAccountName,password)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<UserDetailNewBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(UserDetailNewBean centerDetailBean) {
                        Log.i("5555", "onNext: " + centerDetailBean.getResult().toString());
                        if ("200".equals(centerDetailBean.getCode())) {
                            spUtils.put(AppConstant.TRUE_NAME, centerDetailBean.getResult().getTrueName());
                            spUtils.put(AppConstant.NICKNAME, centerDetailBean.getResult().getNickName());
                            spUtils.put(AppConstant.MOBILE, centerDetailBean.getResult().getMobile());
                            spUtils.put(AppConstant.CREDITID, centerDetailBean.getResult().getCreditID());
                            spUtils.put(AppConstant.EMAIL, centerDetailBean.getResult().getEmail());
                            spUtils.put(AppConstant.PROVINCE, centerDetailBean.getResult().getProvince());
                            spUtils.put(AppConstant.CITY, centerDetailBean.getResult().getCity());
                            spUtils.put(AppConstant.COUNTY, centerDetailBean.getResult().getCountry());
                            spUtils.put(AppConstant.ADDRESS, centerDetailBean.getResult().getAddress());
                            spUtils.put(AppConstant.LEVEL, centerDetailBean.getResult().getLevel());
                            spUtils.put(AppConstant.DOMINNAME, centerDetailBean.getResult().getDomainName());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        tvZhenshixingming.setText(spUtils.getString(AppConstant.TRUE_NAME));//真实姓名
                        nickname.setText(spUtils.getString(AppConstant.NICKNAME));//昵称
                        tvDianhua.setText(spUtils.getString(AppConstant.MOBILE));//手机号码
                        tvShenfenzhenghao.setText(spUtils.getString(AppConstant.CREDITID));//身份证号
                        tvYouxiang.setText(spUtils.getString(AppConstant.EMAIL));//邮箱
                        tvJuzhudiqu.setText(spUtils.getString(AppConstant.PROVINCE) + " " + spUtils.getString(AppConstant.CITY) + " " + spUtils.getString(AppConstant.COUNTY));
                        tvXiangxidizhi.setText(spUtils.getString(AppConstant.ADDRESS));//详细地址
                        Log.e(TAG, "onComplete: "+ activity.spUtils.getString(AppConstant.HEADURL));
                        Glide.with(activity).load(activity.spUtils.getString(AppConstant.HEADURL)).into(civImageHead);
                }
                });


    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 写子线程中的操作,解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    break;

            }
        }
    };

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
//        String JsonData = new GetJsonDataUtil().getJson(this, "province.txt");//获取assets目录下的json文件数据
//
//        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体
        Gson gson = new Gson();
        CityJsonBean cityJsonBean = gson.fromJson(spUtils.getString(AppConstant.JSON_CITY)/*JsonData*/, CityJsonBean.class);
        options1Items=cityJsonBean.getResult();


        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
//        options1Items = jsonBean;

        for (int i=0;i<cityJsonBean.getResult().size();i++){//遍历省份
            List<CityJsonBean.ResultBean.CityBean> CityList = new ArrayList<>();//该省的城市列表（第二级）
            List<List<CityJsonBean.ResultBean.CityBean.CountyBean>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）
            ArrayList<String> CityList1 = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList1 = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c=0; c<cityJsonBean.getResult().get(i).getCity().size(); c++){//遍历该省份的所有城市
                CityList.add(cityJsonBean.getResult().get(i).getCity().get(c));//添加城市
                CityList1.add(cityJsonBean.getResult().get(i).getCity().get(c).getName());//添加城市

                List<CityJsonBean.ResultBean.CityBean.CountyBean> City_AreaList = new ArrayList<>();//该城市的所有地区列表
                ArrayList<String> City_AreaList1 = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (cityJsonBean.getResult().get(i).getCity().get(c).getCounty() == null
                        ||cityJsonBean.getResult().get(i).getCity().get(c).getCounty().size()==0) {
                    City_AreaList1.add("");
                }else {

                    for (int d=0; d < cityJsonBean.getResult().get(i).getCity().get(c).getCounty().size(); d++) {//该城市对应地区所有数据
                        cityJsonBean.getResult().get(i).getCity().get(c).getCounty();

                        City_AreaList.add(cityJsonBean.getResult().get(i).getCity().get(c).getCounty().get(d));//添加该城市所有地区数据
                        City_AreaList1.add(cityJsonBean.getResult().get(i).getCity().get(c).getCounty().get(d).getName());//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
                Province_AreaList1.add(City_AreaList1);
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);
            options2Items2.add(CityList1);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
            options3Items3.add(Province_AreaList1);

        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }

    @OnClick({R.id.iv_back, R.id.rl_nicheng, R.id.rl_dianhua, R.id.rl_zhenshixingming, R.id.rl_shenfenzhenghao, R.id.rl_youxiang, R.id.rl_juzhudiqu, R.id.rl_xiangxidizhi,R.id.rl_xiugaitouxaing})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.rl_xiugaitouxaing:
                showPopupWindow();
                break;
            case R.id.rl_nicheng:
                getDialog("编辑昵称");
                break;
            case R.id.rl_dianhua:
                getDialog("编辑电话");
                break;
            case R.id.rl_zhenshixingming:
                getDialog("编辑姓名");
                break;
            case R.id.rl_shenfenzhenghao:
                getDialog("编辑身份证号");
                break;
            case R.id.rl_youxiang:
                getDialog("编辑邮箱");
                break;
            case R.id.rl_juzhudiqu:
                if (isLoaded) {
                    ShowPickerView();
                } else {
                }
                break;
            case R.id.rl_xiangxidizhi:
                ActivityUtils.startActivity(activity, MyAddressActivity.class);
                break;
        }
    }

    private void getDialog(String tittle) {
        LayoutInflater inflater = getLayoutInflater();
        layout = inflater.inflate(R.layout.dialog,
                (ViewGroup) findViewById(R.id.rl_cardview));
        layout.findViewById(R.id.quxiao).setOnClickListener(this);
        layout.findViewById(R.id.queding).setOnClickListener(this);
        textView = layout.findViewById(R.id.title);
        textView.setText(tittle);
        clearableEditText = layout.findViewById(R.id.et_content);
        dailog = new AlertDialog.Builder(this)
                .setView(layout)
                .show();
    }

    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

    private void ShowPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                options1Items.get(options1).getId();
                Log.i("080", "cityBeans.get(options2).getName(): "+options1Items.get(options1).getId());
                List<CityJsonBean.ResultBean.CityBean> cityBeans = options2Items.get(options1);
                cityBeans.get(options2).getName();
                Log.i("080", "cityBeans.get(options2).getName(): "+cityBeans.get(options2).getName());
                Log.i("080", "cityBeans.get(options2).getName(): "+cityBeans.get(options2).getId());
                List<List<CityJsonBean.ResultBean.CityBean.CountyBean>> lists = options3Items.get(options1);
                List<CityJsonBean.ResultBean.CityBean.CountyBean> countyBeans = lists.get(options2);
                countyBeans.get(options3).getName();
                Log.i("080", "countyBeans.get(options3).getName(): "+countyBeans.get(options3).getName());
                Log.i("080", "countyBeans.get(options3).getName(): "+countyBeans.get(options3).getId());
//                //返回的分别是三个级别的选中位置
//                String tx = options1Items.get(options1).getPickerViewText() +
//                        options2Items.get(options1).get(options2).getCounty().get(options2).getName() +
//                        options3Items.get(options1).get(options2).get(options3).getName();
//                tvJuzhudiqu.setText(options1Items.get(options1).getPickerViewText() + " " + options2Items.get(options1).get(options2) + " " + options3Items.get(options1).get(options2).get(options3));
                tvJuzhudiqu.setText(options1Items.get(options1).getPickerViewText() + " " +  cityBeans.get(options2).getName() + " " +  countyBeans.get(options3).getName());
//                Toast.makeText(activity,tx,Toast.LENGTH_SHORT).show();
                spUtils.put(AppConstant.PROVINCE, options1Items.get(options1).getPickerViewText());
                spUtils.put(AppConstant.CITY, cityBeans.get(options2).getName());
                spUtils.put(AppConstant.COUNTY,  countyBeans.get(options3).getName());
                settingCenter();
            }
        })

                .setTitleText("城市选择")
                .setSubCalSize(16)//确定和取消文字大小
                .setTitleSize(18)//标题文字大小
                .setDividerColor(getResources().getColor(R.color.white))
                .setSubmitColor(getResources().getColor(R.color.colorPrimaryDark))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.colorPrimaryDark))//取消按钮文字颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(16)
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items2, options3Items3);//三级选择器
        pvOptions.show();
    }

    private void settingCenter() {
        Log.i("5555", "settingCenter: " + spUtils.getString(AppConstant.PROVINCE) + spUtils.getString(AppConstant.CITY) + spUtils.getString(AppConstant.COUNTY));
        HttpMethods.getInstanceCenter().info.getSettingCenter(
                spUtils.getString(AppConstant.USER_NAME)
                , spUtils.getString(AppConstant.TRUE_NAME)
                , spUtils.getString(AppConstant.ADDRESS)
                , spUtils.getString(AppConstant.EMAIL)
                , spUtils.getString(AppConstant.NICKNAME)
                , spUtils.getString(AppConstant.MOBILE)
                , spUtils.getString(AppConstant.CREDITID)
                , spUtils.getString(AppConstant.PROVINCE)
                , spUtils.getString(AppConstant.CITY)
                , spUtils.getString(AppConstant.COUNTY)
        )
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<SettingsPersonalBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(SettingsPersonalBean settingsPersonalBean) {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        tvZhenshixingming.setText(spUtils.getString(AppConstant.TRUE_NAME));//真实姓名
                        nickname.setText(spUtils.getString(AppConstant.NICKNAME));//昵称
                        tvDianhua.setText(spUtils.getString(AppConstant.MOBILE));//手机号码
                        tvShenfenzhenghao.setText(spUtils.getString(AppConstant.CREDITID));//身份证号
                        tvYouxiang.setText(spUtils.getString(AppConstant.EMAIL));//邮箱
                        tvJuzhudiqu.setText(spUtils.getString(AppConstant.PROVINCE) + " " + spUtils.getString(AppConstant.CITY) + " " + spUtils.getString(AppConstant.COUNTY));
                        tvXiangxidizhi.setText(spUtils.getString(AppConstant.ADDRESS));//详细地址
                    }
                });

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.quxiao:
                dailog.dismiss();
                break;
            case R.id.queding:
                if ("编辑邮箱".equals(textView.getText())) {
                    //正则判断邮箱，如果符合 就请求网络修改
                    spUtils.put(AppConstant.EMAIL, clearableEditText.getText().toString());
                    settingCenter();
                    dailog.dismiss();
                }
                if ("编辑昵称".equals(textView.getText())) {
                    //正则判断邮箱，如果符合 就请求网络修改
                    if (!clearableEditText.getText().toString().isEmpty()) {
                        spUtils.put(AppConstant.NICKNAME, clearableEditText.getText().toString());
                        settingCenter();
                    } else {
                        ToastFactory.getToast(activity, "昵称不能为空").show();
                        return;
                    }
                    dailog.dismiss();
                }
                if ("编辑电话".equals(textView.getText())) {
                    //正则判断邮箱，如果符合 就请求网络修改
                    dailog.dismiss();
                }
                if ("编辑姓名".equals(textView.getText())) {
                    //正则判断邮箱，如果符合 就请求网络修改
                    dailog.dismiss();
                }
                if ("编辑身份证号".equals(textView.getText())) {
                    //正则判断邮箱，如果符合 就请求网络修改
                    dailog.dismiss();
                }
                break;
        }
    }
    public void updateUserPic(){
        //构建body
        RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("file", BitmapUtil.convertIconToString(compressImage(bitmap)))
                        .addFormDataPart("userName",activity.spUtils.getString(AppConstant.USER_NAME))
                        .addFormDataPart("reversiblePasswd",activity.spUtils.getString(AppConstant.USER_PASSWORD))
                .build();
        Log.e(TAG, "方法执行没 " );
        HttpMethods.getInstanceCenter().info.upDateHead(requestBody)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<HeadBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(HeadBean headBean) {
                        Log.e(TAG, "头像地址 "+headBean.toString() );
                        if (!headBean.getHeadUrl().isEmpty()){
                            if (headBean.getHeadUrl().startsWith("/")){
                                activity.spUtils.put(AppConstant.HEADURL,AppConstant.BASE_URL_HEAD+headBean.getHeadUrl());
                            }else {
                                activity.spUtils.put(AppConstant.HEADURL,AppConstant.BASE_URL+headBean.getHeadUrl());
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "修改头像失败 "+e.toString() );
                    }

                    @Override
                    public void onComplete() {
                        EventBus.getDefault().post("login");

                    }
                });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case Cut_PHOTO:
                if (resultCode == RESULT_OK) {
                    if (bitmap != null && !bitmap.isRecycled()) {
                        // 回收并且置为null
                        bitmap.recycle();
                        bitmap = null;
                    }
                    System.gc();
                    try {
                        bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUriFromCamera));

                        // 将裁剪后的照片显示出来
                        civImageHead.setImageBitmap(ImageUtils.scale(bitmap, civImageHead.getWidth(), civImageHead.getHeight()));
                        updateUserPic();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case PHOTO_ALBUM:
                Log.i("123", "onActivityResult: " + PHOTO_ALBUM);
                if (resultCode == RESULT_OK) {
                    uri = data.getData();
                    if (uri.toString().contains("com.miui.gallery.open")) {
                        uri = getImageContentUri(activity, new File(getRealFilePath(activity, uri)));
                    }
                    if (bitmap != null && !bitmap.isRecycled()) {
                        // 回收并且置为null
                        bitmap.recycle();
                        bitmap = null;
                    }
                    System.gc();
                    try {
                        bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
                        civImageHead.setImageBitmap(ImageUtils.scale(bitmap, civImageHead.getWidth(), civImageHead.getHeight()));
                        updateUserPic();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }

                break;
            default:
                break;
        }
    }
    public static byte[] getFileToByte(File file) {
        byte[] by = new byte[(int) file.length()];
        try {
            InputStream is = new FileInputStream(file);
            ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
            byte[] bb = new byte[2048];
            int ch;
            ch = is.read(bb);
            while (ch != -1) {
                bytestream.write(bb, 0, ch);
                ch = is.read(bb);
            }
            by = bytestream.toByteArray();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return by;
    }

    public byte[] getBitmapByte(Bitmap bitmap){   //将bitmap转化为byte[]类型也就是转化为二进制
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
        try {
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return out.toByteArray();
    }
    public void showPopupWindow() {
        if (popupWindow != null && popupWindow.isShowing()) return;
        View upView = LayoutInflater.from(this).inflate(R.layout.popup_up, null);
        //测量View的宽高
        CommonPopupWindow.measureWidthAndHeight(upView);
        popupWindow = new CommonPopupWindow.Builder(this)
                .setView(R.layout.popup_up)
                .setWidthAndHeight(ViewGroup.LayoutParams.MATCH_PARENT, upView.getMeasuredHeight())
                .setBackGroundLevel(0.5f)//取值范围0.0f-1.0f 值越小越暗
                .setAnimationStyle(R.style.AnimUp)
                .setViewOnclickListener(this)
                .create();

        popupWindow.showAtLocation(findViewById(android.R.id.content), Gravity.BOTTOM, 0, 0);
    }

    public void album() {
        outputImage = new File(Environment.getExternalStorageDirectory(),
                "user_head" + System.currentTimeMillis() + ".jpg");
        try {
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        imageUri = FileProvider.getUriForFile(this,
                "com.ln.lnzw.fileprovider", outputImage); //getApplicationContext().getPackageName() + ".provider"
//        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        Intent intent = new Intent(Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.setType("image/*");
        //允许裁剪
        intent.putExtra("crop", true);
        //允许缩放
        intent.putExtra("scale", true);
        //图片的输出位置
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, PHOTO_ALBUM);
    }

    public void phone1() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        photoFile = createImagePathFile(this);
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);

                                /*
                                * 这里就是高版本需要注意的，需用使用FileProvider来获取Uri，同时需要注意getUriForFile
                                * 方法第二个参数要与AndroidManifest.xml中provider的里面的属性authorities的值一致
                                * */
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        imageUriFromCamera = FileProvider.getUriForFile(this,
                "com.ln.lnzw.fileprovider", photoFile);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUriFromCamera);

        startActivityForResult(intent, Cut_PHOTO); //
    }

    public File createImagePathFile(Activity activity) {
        //文件目录可以根据自己的需要自行定义
        Uri imageFilePath;
        File file = new File(activity.getExternalCacheDir(), USER_IMAGE_NAME);
        imageFilePath = Uri.fromFile(file);
        return file;
    }

    @Override
    public void getChildView(View view, int layoutResId) {
        switch (layoutResId) {
            case R.layout.popup_up:
                TextView camera = (TextView) view.findViewById(R.id.tv_camera);
                TextView phone = (TextView) view.findViewById(R.id.tv_phone);
                Button btnCancel = (Button) view.findViewById(R.id.btn_cancel);
                camera.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        phone1();
                        if (popupWindow != null) {
                            popupWindow.dismiss();
                        }
                    }
                });
                phone.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        album();
                        if (popupWindow != null) {
                            popupWindow.dismiss();
                        }
                    }
                });
                btnCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (popupWindow != null) {
                            popupWindow.dismiss();
                        }
                    }
                });
                view.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        if (popupWindow != null) {
                            popupWindow.dismiss();
                        }
                        return true;
                    }
                });
                break;
        }
    }

    public static Uri getImageContentUri(Context context, File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID},
                MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath}, null);

        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor
                    .getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

    public static String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri)
            return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri,
                    new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }
    public static Bitmap compressImage(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 90;

        while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset(); // 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        return bitmap;
    }
}
